<?php

namespace app\admin\controller\medicine;

use app\common\controller\Backend;
use think\Db;

/**
 * 药品领取
 *
 * @icon fa fa-circle-o
 */
class Get extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Treatment;
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["order"=>['id','code','info_id','status'],"info"=>['id','name']])
                ->with([
                    'order' => function ($query) {
                        $query->withField('id,code,info_id,status');
                    },
                    'info' => function ($query) {
                        $query->withField('id,name');
                    }
                ])
                ->where($where)
                ->where('order.status','in',[1,2])
                //->where('admin_id', 'in', [0])
                ->order('id', $order)
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]['count'] = Db::table('fa_treatment')
                        ->where('order_id',$v['order_id'])
                        ->count();
                }
            }


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $nurse_arr = Db::table('fa_medic')
                ->where('id',$params['nurse_id'])
                ->find();


            //组装数据
            $order_id = $params['id'];
            $params['nurse_name'] = $nurse_arr['name'];
            $params['get'] = 1;
            unset($params['id']);


            $drug = Db::table('fa_drug')
                ->where('order_id',$order_id)
                ->select();

            if (!empty($drug)){
                foreach ($drug as $k=>$v){
                    $find = Db::table('fa_storage')
                        //->where(['medicine_id'=>$v['medicine_id'],'quantity'=>['<>',0]])
                        ->where(['id'=>$v['medicine_id']])
                        //->order(['end_time'=>'asc','id'=>'desc'])
                        ->find();

                    if (empty($find)){
                        $this->error(__($v['medicine_name'].'药品数据为空'));
                    }

                    if (($find['quantity']-$v['count']) < 0){
                        $this->error(__($v['medicine_name'].'药品库存不足'));
                    }

                    $update = Db::table('fa_storage')
                        ->where('id',$find['id'])
                        ->setDec('quantity',$v['count']);

                    $updates = Db::table('fa_medicine')
                        ->where('id',$v['medicine_id'])
                        ->setDec('count',$v['count']);
                }
            }




            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //药品单
        $drug = Db::table('fa_drug')
            ->where('order_id',$row->order_id)
            ->select();

        $nurse = Db::table('fa_medic')
            ->where('type','护士')
            ->select();

        $this->view->assign("row", $row);
        $this->view->assign("drug", $drug);
        $this->view->assign("nurse", $nurse);
        return $this->view->fetch();
    }



    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
